// Loads the .RAW file and stores it in pHeightMap
void LoadRawFile(char *strName, int nSize, BYTE *pHeightMap)
{
	FILE *pFile = NULL;

	// Open the file in read / binary mode.
	pFile = fopen( strName, "rb" );

	// Check to see if we found the file and could open it
	if ( pFile == NULL )
	{
		// Display error message and stop the function
		MessageBox(NULL, "Can't Find The Height Map!", "Error", MB_OK);
		return;
	}

	fread( pHeightMap, 1, nSize, pFile );

	// After we read the data, it's a good idea to check if everything read fine
	int result = ferror( pFile );

	// Check if we received an error
	if (result)
	{
		MessageBox(NULL, "Failed To Get Data!", "Error", MB_OK);
	}

	// Close the file.
	fclose(pFile);
}

int Height(BYTE *pHeightMap, int X, int Y)	// This returns the height from a height map index
{
	if(!pHeightMap) return 0;		// Make sure our data is valid

        if ((X < 0) || (X > MAP_SIZE) || (Y < 0) || (Y > MAP_SIZE)) return 0;

	return pHeightMap[X + (Y * MAP_SIZE)];	// Index into our height array and return the height
}

void SetFogCoord(float depth, float height)
{
	float fogY = 0;

	// Check if the height of this vertex is greater than the depth (needs no fog)
	if(height > depth)
		fogY = 0;
	// Otherwise, calculate the fog depth for the current vertex
	else
		fogY = -(height - depth);

	// Assign the fog coordinate for this vertex using our extension function pointer
	glFogCoordfEXT(fogY);
}

void RenderHeightMap(BYTE pHeightMap[])         // This renders the height map as quads
{
	int X = 0, Y = 0;			// Create some variables to walk the array with.
        VECTOR bl, tl, tr, br;

	if(!pHeightMap) return;			// Make sure our height data is valid

        glBindTexture(GL_TEXTURE_2D, texture[grass_tex].TexID);
        glEnable(GL_TEXTURE_2D);

        glPushMatrix();

        glTranslatef(-1*MAP_SIZE/2,
                     -300,
                     -1*MAP_SIZE/2);

		glBegin( GL_QUADS );		// Render polygons

	for ( X = 0; X < MAP_SIZE; X += STEP_SIZE )
		for ( Y = 0; Y < MAP_SIZE; Y += STEP_SIZE )
		{
                        bl.Set(X, Height(pHeightMap, X, Y), Y);
                        tl.Set(X, Height(pHeightMap, X, Y + STEP_SIZE), Y + STEP_SIZE);
                        tr.Set(X + STEP_SIZE, Height(pHeightMap, X + STEP_SIZE, Y + STEP_SIZE), Y + STEP_SIZE);
                        br.Set(X + STEP_SIZE, Height(pHeightMap, X + STEP_SIZE, Y), Y);

                        glTexCoord2i(0, 0);
			glVertex3i(bl.x, bl.y, bl.z);
			SetFogCoord(g_FogDepth, (float)bl.y);

                        glTexCoord2i(0, 1);
			glVertex3i(tl.x, tl.y, tl.z);
			SetFogCoord(g_FogDepth, (float)tl.y);

                        glTexCoord2i(1, 1);
			glVertex3i(tr.x, tr.y, tr.z);
			SetFogCoord(g_FogDepth, (float)tr.y);

                        glTexCoord2i(1, 0);
			glVertex3i(br.x, br.y, br.z);
			SetFogCoord(g_FogDepth, (float)br.y);
		}
	glEnd();

        glDisable(GL_TEXTURE_2D);
        glPopMatrix();
}




